<template>
  <div class="app-container">
    <!--表单-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="日期">
        <el-date-picker v-model="day" type="date" placeholder="选择要统计的日期" value-format="yyyy-MM-dd" />
      </el-form-item>
      <el-button :disabled="btnDisabled" type="primary" @click="create()">生成</el-button>
      <el-button :loading="downloadLoading" v-show="tableDisabled" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </el-form>
    <el-table
      :data="list"
      v-show="tableDisabled"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="135">
        <template slot-scope="scope">
          {{ scope.$index+1 }}
        </template>
      </el-table-column>
        <el-table-column label="饮品名称" width="600" align="center">
          <template slot-scope="{row}">
            <span>{{ row.drinkName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="550" align="center">
          <template slot-scope="{row}">
            {{ row.number }}
          </template>
        </el-table-column>
    </el-table>
  </div>
</template>

<script>
import daily from '@/api/statistics'
import {parseTime} from "@/utils";
export default {
  data() {
    return {
      day: '',
      btnDisabled: false,
      list: [{
        drinkName: '',
        number: ''
      }],
      tableDisabled: false,
      downloadLoading: false
    }
  },
  methods: {
    create() {
      this.btnDisabled = true
      daily.createStatistics(this.day).then((response) => {
        this.list = response.data.data
        this.btnDisabled = false
        this.$message({
          type: 'success',
          message: '生成成功'
        })
        this.tableDisabled = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['饮品名称', '数量']
        const filterVal = ['drinkName', 'number']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '统计表'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
